﻿using CrmField.Win8App.Data;
using CRMField.Win8App.Common;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Networking.PushNotifications;
using Windows.UI.Popups;

namespace CrmField.Win8App.Common
{
    public class WnsChannelManager
    {
        public static PushNotificationChannel Channel { get; set; }

        public static async Task SetupChannel()
        {
            if (App.IsInternetAvailable())
            {
                try
                {
                    WnsChannelManager.Channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
                    await NotifyCrm();
                }
                catch (Exception ex)
                {
                    var messageDialog = new MessageDialog("Could not create WNS channel & notify CRM of the WNS Channel. \n" + ex.Message);
                    messageDialog.ShowAsync();
                }
            }
        }

        public static async Task NotifyCrm()
        {
            try
            {

                if (CrmContextManager.IsValid())
                {

                    var oldChannelUri = Windows.Storage.ApplicationData.Current.LocalSettings.Values["WnsChannel"] as string;



                    if (string.IsNullOrEmpty(oldChannelUri))
                    {
                        // No old channel we create an store new one in CRM
                        var newChannel = new Entity(fsapp_clientchannel.EntityLogicalName);
                        newChannel["fsapp_uri"] = Channel.Uri;
                        var createRequest = new CreateRequest() { Target = newChannel };

                        var service = await CrmContextManager.GetConnectionAsync();
                        await service.ExecuteAsync<CreateRequest, CreateResponse>(createRequest);

                        Windows.Storage.ApplicationData.Current.LocalSettings.Values["WnsChannel"] = Channel.Uri;

                    }
                    else
                    {
                        if (Channel.Uri != oldChannelUri)
                        {
                            //We have a new channel with a different Uri. Notify CRM of the change
                            var service = await CrmContextManager.GetConnectionAsync();

                            var query = new FetchExpression(@"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                                                                  <entity name='fsapp_clientchannel'>
                                                                    <attribute name='fsapp_clientchannelid' />
                                                                    <attribute name='fsapp_uri' />
                                                                    <attribute name='createdon' />
                                                                    <order attribute='fsapp_uri' descending='false' />
                                                                    <filter type='and'>
                                                                      <condition attribute='statecode' operator='eq' value='0' />
                                                                      <condition attribute='ownerid' operator='eq-userid' />
                                                                    </filter>
                                                                  </entity>
                                                                </fetch>");

                            //Retrieve Channel
                            IEnumerable<fsapp_clientchannel> result = await service.RetrieveMultipleAsync<fsapp_clientchannel>(query);

                            foreach (var item in result)
                            {
                                if (item.fsapp_uri == oldChannelUri)
                                {
                                    //Update Relevant Channels
                                    Entity updatedChannel = new Entity(fsapp_clientchannel.EntityLogicalName);
                                    updatedChannel.Attributes["fsapp_uri"] = Channel.Uri;
                                    updatedChannel.Id = item.fsapp_clientchannelId.Value;
                                    await service.UpdateAsync(updatedChannel);
                                }
                            }

                            // Store new channel
                            Windows.Storage.ApplicationData.Current.LocalSettings.Values["WnsChannel"] = Channel.Uri;

                        }
                    }
                }
            }




            catch (Exception ex)
            {
                var messageDialog = new MessageDialog("Could not notify CRM of the WNS Channel. \n" + ex.Message);
                messageDialog.ShowAsync();
            }
        }
    }
}
